using System;
using System.Collections.Generic;
using System.Text;

using gudusoft.gsqlparser;
using gudusoft.gsqlparser.Units;

namespace topClause
{
    class topClause
    {
        static void Main(string[] args)
        {
            TGSqlParser sqlparser = new TGSqlParser(TDbVendor.DbVMssql);
            sqlparser.SqlText.Text = @"SELECT ClientID, FirstName + ' ' + LastName AS FullName, Phone
FROM Client
WHERE ClientID IN ( 1, 2, 3, 4 )
";
            int iRet = sqlparser.Parse();
            TSelectSqlStatement select = (TSelectSqlStatement)sqlparser.SqlStatements[0];
            modifyTopClause(select, "top 10");
            Console.WriteLine(pp(select.AsText,TDbVendor.DbVMssql));

            sqlparser.SqlText.Text = @"SELECT top 4 ClientID, FirstName + ' ' + LastName AS FullName, Phone
FROM Client
WHERE ClientID IN ( 1, 2, 3, 4 )
";
            iRet = sqlparser.Parse();
            select = (TSelectSqlStatement)sqlparser.SqlStatements[0];
            modifyTopClause(select, "top 10");
            Console.WriteLine(pp(select.AsText, TDbVendor.DbVMssql));

   
        }

        /// <summary>
        /// 
        /// add new top clause if there is no top clause in select already, 
        /// otherwise, just ignore new top clause.
        /// </summary>
        /// <param name="select"></param>
        /// <param name="newstr"></param>
        static void modifyTopClause(TSelectSqlStatement select, string newstr)
        {
            if (select.topclause == null)
            {
                select.topclauseText = newstr;
            }
        }

        static string pp(string sql, TDbVendor vendor)
        {
            TGSqlParser parser = new TGSqlParser(vendor);
            parser.SqlText.Text = sql;
            if (parser.PrettyPrint() == 0)
            {
                return parser.FormattedSqlText.Text;
            }
            else
            {
                return sql;
            }
        }
    }
}
